package com.ghao.douban.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.Serializable;

@Controller
public class AuthController {

    @GetMapping("index")
    public String index(){
        return "index";
    }

    /*
     * 认证
     */
    @GetMapping("auth/login")
    @ResponseBody
    public String login(String username, String password){

        //这里不需要获得securityManager，springConfig中已经配置了
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            //如果认证失败跳转到index
            return "forward:/index";
        }
        Serializable id = subject.getSession().getId();
        return "success";
    }

    @GetMapping("success")
    public String success(){
        return "success";
    }

    @GetMapping("need/perm")
    @RequiresPermissions(value = "perm", logical = Logical.OR)
    public String needPerm(){
        return "permission";
    }

    @GetMapping("noPerm")
    public String noPerm(){
        return "noPerm";
    }

    @GetMapping("auth/logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "index";
    }
}
